package com.bdqn.demo.filter;

import com.bdqn.demo.pojo.User;
import com.bdqn.demo.utils.JwtUtils;
import com.bdqn.demo.utils.ThreadHold;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (token != null){
            try {
                JwtUtils.parse(token);
                User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                ThreadHold.set(user);
            } catch (Exception e) {
                response.setStatus(401);
                return;
            }
        }
        filterChain.doFilter(request,response);
    }
}
